// Functions for index page
        
           //Validate the Email form for correct input
           function validateForm() {
		        var x=document.forms["email_form"]["email"].value
		        var atpos=x.indexOf("@");
		        var dotpos=x.lastIndexOf(".");
		        if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
		            return false;
		        } else {
		        	return true;
		        }
	        } 
		    
	        // String startsWith function
	        // Test whether the pattern is located at the start of the string
	        String.prototype.startsWith = function(s){
	           if( this.toLowerCase().indexOf(s.toLowerCase()) == 0 ) return true;
	           return false;
	        }

            // Document loaded
	        jQuery(document).ready(function() {
	        	
    			jQuery('#load').hide();
        		jQuery('a[rel*=facebox]').facebox();  
        	
        		var availableTags = [
        		         			"SELECT",
        		         			"FROM",
        		         			"ORDER BY",
        		         			"WHERE",
        		         			"TOP",
        		         			"IN",
        		         			"AND",
        		         			"OR",
        		         			"WITH",
        		         			"DESC",
        		         			"ASC",
        		         			"JOIN",
        		         			"AS",
        		         			"HAVING",
        		         			"ABS",
        		         			"count"
        		         		];
        		
        		function contains(a, obj) {
        		    var i = a.length;
        		    while (i--) {
        		       if (a[i] === obj) {
        		           return true;
        		       }
        		    }
        		    return false;
        		}

        		
        		function split( val ) {
        			return val.split(' ');
        		}
        		
        		function extractLast( term ) {
        			return_val = split( term ).pop() 
        			if (return_val.indexOf(',')>-1){
        				return_val = return_val.split(',').pop();
        			}
        			return return_val;
        		}

        		function get_metadata_content (data) {
        			var content = document.createElement('div');
        			content.innerHTML = data;
        		    var tr = content.getElementsByClassName('heading');
        		    var tr2 = content.getElementsByClassName('expand');
        		    for(var i=0;i<tr.length;i++){
        		    	var str = tr[i].innerHTML.split(' ');
        		    	availableTags.push(str[0]);
				    }
        		    for(var i=0;i<tr2.length;i++){
        		    	if (!contains(availableTags,tr2[i].innerHTML)){
        		    		availableTags.push(tr2[i].innerHTML);
        		    	}
        		    }
        		
        		}


				var table_names = [];
				
				function save_table_names (){
					table_names = [];
					jQuery('.heading').each(function() {
					   table_names.push(jQuery(this).text().trim()); 
					});
				}
				
        		
        		function extractTables (term) {
					var line = term;
        		    var table_list = [];
        		    for (x in table_names) {
						if ((term.indexOf(" "+ table_names[x]+ " ")>-1) || (term.indexOf(" "+ table_names[x]+ ",")>-1)						
					       || (term.indexOf(","+ table_names[x]+ " ") >-1) ||						
						   (term.indexOf(","+ table_names[x] + ",") >-1)){
							 table_list.push (table_names[x]);
						 }						
					}
        		    return table_list;
        		}
            		
        		
        		function init_autocomplete (input_string){
	        		jQuery( input_string )
	        		// don't navigate away from the field on tab when selecting an item
	       			.bind( "keydown", function( event ) {
	       				if ( event.keyCode === jQuery.ui.keyCode.TAB &&
	       						jQuery( this ).data( "autocomplete" ).menu.active ) {
	       					event.preventDefault();
	       				}
	       			})
	       			.autocomplete({
	       				minLength: 0,
	       				source: function( request, response ) {
	       					if (extractLast(request.term)==''){
	       						return false;
	       					}
	       					// delegate back to autocomplete, but extract the last term
	       					var tables = extractTables(request.term);
	       					if (tables.length>0) {
		       						var tags = [
		            		         			"SELECT",
		            		         			"FROM",
		            		         			"ORDER BY",
		            		         			"WHERE",
		            		         			"TOP",
		            		         			"IN",
		            		         			"AND",
		            		         			"OR",
		            		         			"WITH",
		            		         			"DESC",
		            		         			"ASC",
		            		         			"JOIN",
		            		         			"AS",
		            		         			"HAVING",
		            		         			"ABS",
		            		         			"count"
		            		         		];
		       				
				       			for (x in table_names){
				       				tags.push(table_names[x]);
				       			}
				       			
	       						jQuery('.heading').each(function() {
	       							for (x in tables) {
	       							 if (jQuery(this).text().trim() == tables[x].trim()){
	       								  var cols = jQuery(this).siblings().children().find('a');
	       								  for (var i=0;i<cols.length;i++){	 
	       									  tags.push(cols[i].firstChild.data.trim());
	       								  }
	       							   }    							  
	       							}
	       							
	       						});

	       						var filteredArray = jQuery.map(tags, function(item) {
		       						if( item.startsWith( extractLast(request.term))){
							        	return item;
							        } else {
							            return null;
							        }
							    });
	       						
	       					} else {
		       					var filteredArray = jQuery.map(availableTags, function(item) {
									if( item.startsWith( extractLast(request.term))){
							        	return item;
							        } else {
							            return null;
							        }
							    });
	       					}
	       					response( jQuery.ui.autocomplete.filter(
	       							filteredArray, extractLast( request.term ) ) );
	       				},
	       				focus: function() {
	       					// prevent value inserted on focus
	       					return false;
	       				},
	       				select: function( event, ui ) {
	       					var terms = split( this.value);
	       					//var terms = this.value.split(/[\s,]+/);
	       					var new_array = [];
	       					for( i in terms ){
	       						if (terms[i].indexOf(',')>0){
	       							temp_array = terms[i].split(',');
	       							for (x in temp_array) {
	       								new_array.push(temp_array[x]);
	       								new_array.push(',');
	       							}
	       							new_array.pop();
	       						} else {
	       							new_array.push(terms[i]);
	       						}
	       						
	       					}
	       					terms = new_array;
	       					// remove the current input
	       					terms.pop();
	       					// add the selected item
	       					terms.push( ui.item.value );
	       					// add placeholder to get the comma-and-space at the end
	       					terms.push( "" );
	       					this.value = terms.join( " " );
	       					return false;
	       				}
	       			
	        		});
        		}
	
        		// Following line is experimental
        		init_autocomplete("#textfield");
	
        		
        		jQuery('form').find("input[type='submit']").removeAttr('disabled');
	            var xhr;
	            
	             
	            // Handle ADQL form submission
	        	jQuery('.form').each(function() {
	                    jQuery(this).submit(function(){
	                    	if (jQuery('#metadata').css('display')=='none'){
	                    		jQuery('#settings_form').slideUp('slow');
	                    	}
	                    	
		            	    var submitButton = jQuery(this).find("input[type='submit']");
		            		var input_string = jQuery("textarea#textfield").val();
		            		var selected_endpoint = jQuery("#tap_endpoint").val();
		            		var table_mode = jQuery("input[name=table_mode]:checked").val();
		            
		            		if (selected_endpoint==''){
		                     	jQuery('#error').html('Please select from the list of endpoints');	
		            			jQuery('#error').fadeIn('fast');
                             	jQuery('#error').delay(3500).fadeOut('slow');
		            		} else if (input_string!=''){
			                    jQuery(submitButton).attr("disabled", "true");
			                    jQuery('#results').fadeOut('fast');
			                    jQuery('#load').fadeIn('normal');
			                    jQuery('#loading_options').fadeIn('normal');
        					    jQuery("#metadata").slideUp();
								var ready = false;
			    				xhr = jQuery.ajax({
			                            type: "POST",
			                            data: {textfield : input_string,generated_tap : selected_endpoint, table_mode : table_mode},
			                            timeout: 1000000,
			                            error: function() {
				                               jQuery('form').find("input[type='submit']").removeAttr('disabled');
				                               jQuery('#loading_options').hide();
				                               jQuery('#load').hide();				                          
			                            },
			                            success: function(data) {
				             	
			                            	if (data==""){
				                            	jQuery('#loading_options').hide();
					                            jQuery('#load').hide();
					                            jQuery('form').find("input[type='submit']").removeAttr('disabled');						                     					                                              
				                          	} else if (data=="Error" || data == null || data == "None") {
				                            	jQuery('#loading_options').hide();
					                            jQuery('#load').hide();
					                            jQuery('form').find("input[type='submit']").removeAttr('disabled');						                     
				                          		jQuery('#error').html('Your request returned an error.. Please check your query and try again');	
						            			jQuery('#error').fadeIn('fast');
				                             	jQuery('#error').delay(3500).fadeOut('slow');                           
				                          	}  else if (data=="Query_Error") {
				                            	jQuery('#loading_options').hide();
					                            jQuery('#load').hide();
					                            jQuery('form').find("input[type='submit']").removeAttr('disabled');						                     
				                          		jQuery('#error').html('Please choose a column to order your results by');	
						            			jQuery('#error').fadeIn('fast');
				                             	jQuery('#error').delay(3500).fadeOut('slow');                           
				                          	}  else if (data == "MAX_ERROR"){
				                            	jQuery('#loading_options').hide();
					                            jQuery('#load').hide();
					                            jQuery('form').find("input[type='submit']").removeAttr('disabled');						                     
				                          		jQuery('#error').html('The results of the requested query exceeded the Max filesize limit.. Please try a different query');	
						            			jQuery('#error').fadeIn('fast');
				                             	jQuery('#error').delay(3500).fadeOut('slow');                           				                         		
			                            	} else {
				                            	jQuery('#loading_options').hide();
					                            //jQuery('#load').hide();
				                          		jQuery('#results').hide();	
   					                            jQuery('form').find("input[type='submit']").removeAttr('disabled');				                          		
   					                            try {
   					                            	var result_array = [];
   					                            	result_array = jQuery.parseJSON(data);
   					                            	var row_length = parseInt(result_array[1]);
   					                            } catch (ex) { 
   						                     		jQuery('#error').html("Query returned invalid data.. Please try another query");
	   					        					console.log(ex);
   						                     		jQuery('#error').fadeIn('normal');
	   					        					jQuery('#error').delay(3800).fadeOut('slow');
	   					        					jQuery('#load').hide();
	   					        					result_array = "error";
   					                            } 
   					                          if (result_array.length<1 || row_length <= 0 || row_length == null){
				                          			jQuery('#error').html('Your query returned 0 results');	
				                          			jQuery('#error').fadeIn('fast');
					                             	jQuery('#error').delay(3500).fadeOut('slow');
					                             	jQuery('#load').hide();
				                          		} else if (result_array != "error"){
					                          		jQuery('#results').html(result_array[2][0]);
					                          		var pathname = jQuery('#temp_file').val();
					            					var data_source = "";
					            					jQuery('#load').hide();
					            					jQuery('#results').append('<table cellpadding="0" cellspacing="0" border="0" class="datatables" id="votable"></table> ' );                            	
					                          		var col = [];
					                          		var error_bool = false;
					                          	  	
					                          		for (i=0;i<result_array[0].length;i++) {
					                          			col.push({"sTitle" : result_array[0][i]});
						                            }
						                      		
					            					if (table_mode == "interactive") {
					            						var json_result_data = jQuery.parseJSON(jQuery('#hidden_json_results').val());
					            						if (json_result_data!=null){
						            						var oTable = jQuery('.datatables').dataTable( {
								                        		"bJQueryUI" : true,
								                        		"sPaginationType": "full_numbers",
								                        		"sDom" : 'T<"clear">R<"H"Clfr>t<"F"ip>',
								                        		"bProcessing" : true,
								                        		//"bServerSide" : true,
								                        		"aaData" : json_result_data,
								                        		"aoColumns" : col,					                        		
								                        		 //"bScrollCollapse": true,
								                        		"bAutoWidth": false,
								                        		"sScrollX": "100%",
								                        		"sSwfPath" : "media/swf/copy_cvs_xls.swf"
								                            }); //end oTable
								                      		jQuery('#results').fadeIn();
					            						} else {
					    					          		jQuery('#error').html("There was an error processing your request.. Please try another query");
			   					        					jQuery('#error').fadeIn('normal');
			   					        					jQuery('#error').delay(3800).fadeOut('slow');   
			   					        					jQuery('#results').hide();
									                        jQuery('#load').hide();
						        						}
					            					} else {
					            						var oTable = jQuery('.datatables').dataTable( {
							                        		"bJQueryUI" : true,
							                        		"sPaginationType": "full_numbers",
							                        		"sDom" : 'T<"clear">R<"H"Clfr>t<"F"ip>',
							                        		"bProcessing" : true,
							                        		"bServerSide" : true,
							                        		//"aaData":result_array[1], 
							                        		"aoColumns" : col,					                        		
							                        		//"bScrollCollapse": true,
							                        		"bAutoWidth": false,
							                        		"sScrollX": "100%",
							                        		"sSwfPath" : "media/swf/copy_cvs_xls.swf",
							                        		"sAjaxSource" : '/data_tables_processing',
															"fnServerData" : function ( sSource, aaData, fnCallback ) {
																				 aaData.push({'name' : 'pathname', 'value' : pathname});
																				  jQuery.ajax({
																	           		 "dataType": 'json',
																	                 "type": "POST",
																	                 "url": sSource,
																	                 "data": aaData, 
																                     timeout: 1000000,
																                     "error": function(data){
																 		          		if (!error_bool){ 
																 		          			console.log(data);
																	                    	error_bool = true;
																	                        jQuery('#load').hide();
																				            jQuery('#error').html("Query returned invalid data.. Please try another query");
											   					        					jQuery('#error').fadeIn('normal');
											   					        					jQuery('#error').delay(3800).fadeOut('slow');   
																	 		        
																 		          		}		
																 		          	},
																	                 "success": function(data){
																	                	
			  	  	 														          	 if (data==null){
			  	  	 														          		if (!error_bool){ 
																	                		 	error_bool = true;
				  	  	 														          		jQuery('#error').html("There was an error processing your request.. Please try another query");
												   					        					jQuery('#error').fadeIn('normal');
												   					        					jQuery('#error').delay(3800).fadeOut('slow');   
												   					        					jQuery('#results').hide();
																		                        jQuery('#load').hide();
																		                    																	             		
			  	  	 														          		}
			  	  	 														          	} else {
																		                    error_bool = false;
																	                        jQuery('#load').hide();
																		                    jQuery('#results').fadeIn('fast');
																		             		fnCallback(data);															                	 
																			           	}
																	                 }
																	              });  //end ajax call
																				 
																
															} //end fnServerData function
							                        		
							                            }); //end oTable	
					            					}
					                         
						                            oTable.fnAdjustColumnSizing(true);                       
						                            
				                          		}
				                          	}
			           					}
			                    });
	            			} else {
	                     		jQuery('#error').html("Please enter a query");
	        					jQuery('#error').fadeIn('normal');
	        					jQuery('#error').delay(3800).fadeOut('slow');
	        					jQuery('#load').hide();
	            			}
		            		
	                   	    return false;
	            		
	                     });
	        	});
	            
	            //Stop Query Button Clicked: Cancel previous request
	       		jQuery(".myButtonStop").click(function() {
	                jQuery('.form').find("input[type='submit']").removeAttr('disabled');
	                jQuery('#load').fadeOut('fast');
	                jQuery('#loading_options').fadeOut('normal');
	                xhr.abort();
	                return false;
	       		});
	            
 		       	//Email Query Button Clicked: Cancel previous request, Load Email submission contents
       		 	jQuery(".myButtonEmail").click(function() {
	        	    xhr.abort();
	        		jQuery('.form').find("input[type='submit']").attr("disabled", "true");
	                jQuery('#load').fadeOut('fast');
	                jQuery('#loading_options').fadeOut('normal');
	                jQuery('#send_email').slideDown();
	                return false;
	        	});
	            
	       		//Cancel Email Button Clicked: Slide up the email submission content
	        	jQuery(".email_cancel").click(function() {
	        	    jQuery('#send_email').slideUp();
	                jQuery('form').find("input[type='submit']").removeAttr('disabled');
	        	    return false;
	       		});
	        	
	        	//Email form submission: Validate for user endpoint, query selection and email input
	        	//Send asynchronous POST request to re-initialize query, which will be sent to clients email 
	        	jQuery('.email_form').submit(function() {
	            	var input_query = jQuery('textarea#textfield.textfield').val();
	        		var input_email = $$("input#email").val();
            		var tap_endpoint = jQuery('#tap_endpoint').val();
            		
            		if (tap_endpoint==''){
                 		jQuery('#error').html("Please select from the list of TAP endpoints");
    					jQuery('#error').fadeIn('normal');
    					jQuery('#error').delay(3800).fadeOut('slow');
            		} else if (input_query==''){
                 		jQuery('#error').html("Please enter a query");
    					jQuery('#error').fadeIn('normal');
    					jQuery('#error').delay(3800).fadeOut('slow');
	        		} else if (validateForm()){
	                    jQuery('form').find("input[type='submit']").removeAttr('disabled');
		        		jQuery('#send_email').slideUp();	    
		        		jQuery.ajax({
	                        type: "POST",
	                        url: "send_email",
	                        data: {email : input_email, query : input_query, generated_tap : tap_endpoint},
	                        timeout: 1000000,
	                        error: function() {
	                        	jQuery('#email_message').html('There was an error processing you request');
	                        	jQuery('#email_message').fadeIn('normal');
	    	                   	jQuery('#email_message').fadeOut(2500);
	                        	
	                        },
	                        success: function(data) {
	                        	jQuery('#email_message').html('An email with your results will arrive shortly');
	                        	jQuery('#email_message').fadeIn('normal');
	    	                   	jQuery('#email_message').fadeOut(2500);

	            	        }
	                    });
	        		} else {
                 		jQuery('#error').html("Please enter a valid email");
    					jQuery('#error').fadeIn('normal');
    					jQuery('#error').delay(3800).fadeOut('slow');
	        		}
	               	return false;	        	
	       		 });
	            

	          // Hide Meta-data button: Toggle the metadata content  
	      	  jQuery(".metadata_cancel").click(function() {
	           		jQuery("#metadata").slideToggle();
					jQuery('#load').hide();
		
	          });    
	        
	      	  //Metadata Toggle button clicked: Send POST request to server to retrieve metadata for selected endpoint
	      	  //If Metadata already loaded, simply toggle displaying the content 
	       	  jQuery(".toggle_metadata").click(function() {
            		var display = jQuery('#metadata').css('display');
            		var tap_endpoint = jQuery('#tap_endpoint').val();
           		    if (jQuery('#tables').html()!=""){
					    jQuery("#metadata").slideToggle();
           		    } else if (tap_endpoint==''){
                 		jQuery('#error').html("Please select from the list of TAP endpoints");
    					jQuery('#error').fadeIn('normal');
    					jQuery('#error').delay(3800).fadeOut('slow');
           			} else if (display=='none'){
						jQuery('#load').hide();
	                    jQuery('#load').fadeIn('normal');
		       			jQuery.ajax({
	                            type: "POST",
	                            data: {display : 'yes',generated_tap : tap_endpoint},
	                            timeout: 30000,
	                            error: function() {
	                            	jQuery('#load').hide();	                          
			                 		jQuery('#error').html("There was an error executing your request. Please try again");
			    					jQuery('#error').fadeIn('normal');
			    					jQuery('#error').delay(3800).fadeOut('slow');
								},
	                            success: function(data) {
	                            	if (data==""){
	                            		jQuery('#load').hide();	                      
				                 		jQuery('#error').html("There was an error executing your request.The TAP URl you are using may be unavailable" );
				    					jQuery('#error').fadeIn('normal');
				    					jQuery('#error').delay(3800).fadeOut('slow');
	                            		
	                            	} else {
		                            	jQuery('#tables').html(data).hide().fadeIn('fast');
										jQuery(".meta_content").hide();
										jQuery(".column_content").hide();
										jQuery('#load').hide();
									    jQuery("#metadata").slideToggle();
									    availableTags = [
							        		         			"SELECT",
							        		         			"FROM",
							        		         			"ORDER BY",
							        		         			"WHERE",
							        		         			"TOP",
							        		         			"IN",
							        		         			"AND",
							        		         			"OR",
							        		         			"WITH",
							        		         			"DESC",
							        		         			"ASC",
							        		         			"JOIN",
							        		         			"AS",
							        		         			"HAVING",
							        		         			"ABS",
							        		         			"count"
							        		         		];
									    get_metadata_content(data);
										save_table_names();
									    init_autocomplete("#textfield");
	                            	}
	                            }
	                    });
					} else {
						jQuery('#load').hide();
					    jQuery("#metadata").slideToggle();

					}
	               	return false;	        	
								
	       	  });       
					
	          //Toggle content loading for metadata information  
	          jQuery('.heading').live('click',function(){ 
					jQuery(this).next().next().slideToggle(500);
	   	      });
	          jQuery('.column_heading').live('click',function(){ 
					jQuery(this).next().slideToggle(500);
	   	      });


		
			  jQuery('#cache_or_fetch input').change(function() {
					    jQuery("#endpoints_form").slideUp(500);
					    jQuery('#overflow').delay(3800).html("");   
			  });		    

		    		  
			  
	   	      //Toggle Endpoints button clicked:
	   	      //Send POST request with variables signaling to the server to fetch endpoints from Registry	  
       		  jQuery("#toggle_endpoints").click(function() {
				var use_cached_endpoints = "0";  
				use_cached_endpoints = jQuery("input[name=cache_selection]:checked").val();     
			        if (jQuery('#overflow').html()=="") {
		                jQuery('#load').fadeIn('normal');
		                jQuery('#processing').fadeIn('normal');
	           			jQuery.ajax({
		               		traditional: true,
		                    type: "POST",
		                    dataType: "text",
		                    data: {endpoint_form : 'display', use_cached_endpoints : use_cached_endpoints},
		                    timeout: 1000000,
		                    error: function() {
		                 		jQuery('#error').html("There was an error executing your request. Please try again");
		  		  				jQuery('#error').fadeIn('normal');
		    	                jQuery('#error').delay(3800).fadeOut('slow');
		            			jQuery('#load').hide();
				                jQuery('#processing').hide();
		                    },
		                    success: function(data) {		                    
	            				jQuery('#load').hide();
				                jQuery('#processing').hide();		
		                    	if (data!=""){
				    		         if (jQuery("input[name=cache_selection]:checked").val()== use_cached_endpoints) {
		            					jQuery("#endpoints_form").slideToggle(500);
		            					jQuery("#overflow").html(data).fadeIn('normal');
				    
						             }
				    			} else {
				    				jQuery("#overflow").html("");
				    				jQuery('#error').html("There was an error processing your request.<br> (The endoint or registry may be temporarily unavailable)<br><br><br>");
				    				jQuery('#error').fadeIn('normal');
				  					jQuery('#error').delay(3800).fadeOut('slow');
				    			}
		                    }
		                });
	           		} else {
	        			jQuery("#endpoints_form").slideToggle(500);
	        		}
	               	return false;	        	

	   		  });
		      	

			  
	          // Endpoint form submitted: Fetch Endpoint selection
	          // Send list of URLs to server, then load the returned data to a hidden input variable
       		  jQuery('.endpoints_form').submit(function() {
	       		var selected_endpoints = "";
	       		var count = 0;
	       		jQuery('#endpoints_form input:checked').each(function() {
	       			selected_endpoints+= "  " + (jQuery(this).attr('name'));
	       			count = count + 1;
	       		});
       			if (selected_endpoints==""){
             		jQuery('#error').html("Please select from the list of TAP endpoints");
					jQuery('#error').fadeIn('normal');
					jQuery('#error').delay(3800).fadeOut('slow');
        		} else {       			
        			jQuery('#load').hide();
                    jQuery('#load').fadeIn('normal');
				    jQuery("#metadata").slideUp();
				    jQuery('#tables').html("");
     				if (count>1){
				    // Display a div allowing user to enter prefixes
				    	 var content = "";
				   		 jQuery("#prefixes").slideDown('slow');
				   		 content = "<b> Enter a prefix for each endpoint, or leave empty for automatic generation</b><br><br>";	
				   		 jQuery('#endpoints_form input:checked').each(function() {
			       			content+= jQuery(this).attr('name') + '&nbsp;&nbsp;<input type="textfield" name="' + jQuery(this).attr('name') +  '" id="' + jQuery(this).attr('name') +  '"/><br><br>';
			       	     });
				   		 
				    	 jQuery("#prefixes").html(content);
				   		 jQuery("#prefixes").dialog({
				   			resizable: false,
				   			width: 700,
				   			modal: true,
			     			closeOnEscape: false,
				    		open: function(event, ui) { jQuery(".ui-dialog-titlebar-close").hide(); },
				   			buttons: {			
				   			    Proceed: function() {
   				   			        jQuery(this).dialog("close");
   				   			    	var prefix_array = jQuery('#prefixes input').serializeArray();   			         
   									prefix_array = JSON.stringify(prefix_array);
   				   			    	jQuery.ajax({
   					               		traditional: true,
   				                        type: "POST",
   				                        data: {tap_endpoints : selected_endpoints, prefixes : prefix_array},
   				                        timeout: 100000,
   				                        error: function() {
   				                     		jQuery('#error').html("There was an error executing your request. The TAP factory endpoint may be down for maintenance.");
   				    						jQuery('#error').fadeIn('normal');
   				    						jQuery('#error').delay(3800).fadeOut('slow');
   				    		    			jQuery('#load').hide();
   				    		    		    
   				                        },
   				                        success: function(data) {
   				                        	availableTags = [
   						        		         			"SELECT",
   						        		         			"FROM",
   						        		         			"ORDER BY",
   						        		         			"WHERE",
   						        		         			"TOP",
   						        		         			"IN",
   						        		         			"AND",
   						        		         			"OR",
   						        		         			"WITH",
   						        		         			"DESC",
   						        		         			"ASC",
   						        		         			"JOIN",
   						        		         			"AS",
   						        		         			"HAVING",
   						        		         			"ABS",
   						        		         			"count"
   						        		         		];
   								    
   				                        	if (data!=""){
   				                        		jQuery("#tap_endpoint").val(data);
   				                				jQuery('#load').hide();
   				                				jQuery("#endpoints_form").slideToggle(500);
   				        					} else {
   				                         		jQuery('#error').html("There was an error executing your request. Please check your input and try again");
   					    						jQuery('#error').fadeIn('normal');
   					    						jQuery('#error').delay(3800).fadeOut('slow');
   				                         		jQuery('#load').hide();

   				        					}

   				                        }
   				                    });

				   			    
				   			    },
				   			    Cancel: function() {
				   			    	jQuery('#load').hide();
	   			  			    	jQuery(this).dialog("close");
				   			    }
				   			}
				   		});
				   		 
				    } else {
				    	jQuery.ajax({
			               		traditional: true,
		                        type: "POST",
		                        dataType: "text",
		                        data: {tap_endpoints : selected_endpoints},
		                        timeout: 100000,
		                        error: function() {
		                     		jQuery('#error').html("There was an error executing your request. The TAP factory endpoint may be down for maintenance.");
		    						jQuery('#error').fadeIn('normal');
		    						jQuery('#error').delay(3800).fadeOut('slow');
		                        },
		                        success: function(data) {
		                        	availableTags = [
					        		         			"SELECT",
					        		         			"FROM",
					        		         			"ORDER BY",
					        		         			"WHERE",
					        		         			"TOP",
					        		         			"IN",
					        		         			"AND",
					        		         			"OR",
					        		         			"WITH",
					        		         			"DESC",
					        		         			"ASC",
					        		         			"JOIN",
					        		         			"AS",
					        		         			"HAVING",
					        		         			"ABS",
					        		         			"count"
					        		         		];
							    
		                        	if (data!=""){
		                        		jQuery("#tap_endpoint").val(data);
		                				jQuery('#load').hide();
		                				jQuery("#endpoints_form").slideToggle(500);
		        						
		        					} else {
		                         		jQuery('#error').html("There was an error executing your request. The TAP factory endpoint may be down for maintenance.");
			    						jQuery('#error').fadeIn('normal');
			    						jQuery('#error').delay(3800).fadeOut('slow');
		                         		jQuery('#load').hide();

		        					}

		                        }
		                    });

				    }
        		}

               	return false;
       		  });
       	
    
	          //Toggle check-all/uncheck all checkboxes
       		  jQuery('#select_all').click(function() {
       			  	if(jQuery('#select_all').html()=="Check All"){
             			jQuery('#endpoints_form').find(':checkbox').attr('checked', 'checked');
             			jQuery('#select_all').html("Uncheck All");
       			  	} else {
       				  	jQuery('#endpoints_form').find(':checkbox').removeAttr("checked");
         				jQuery('#select_all').html("Check All");
       			  	}
	      	  });
       		 
	          
	   	      //Toggle Endpoints button clicked:
	   	      //Send POST request with variables signaling to the server to fetch endpoints from Registry	  
       		  jQuery("#settings").click(function() {
			  		jQuery('#settings_form').slideToggle('slow');
       		  });
		    
	          
	          
      	  });
	          
	    